<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Model\AdminOrder;
use DB;

class RollbackOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $orderId;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($orderId)
    {
        $this->orderId = $orderId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 获取插入的订单的状态
        $status = DB::table('shop_orders')->where('id', $this->orderId)->value('status');

        //如果没付款，就找到订单id对应的所有的详情信息
        if ($status == 1) {
            $arr = DB::table('shop_order_details')->select('attr_id', 'buynum')->where('order_id', $this->orderId)->get()->toArray();

            //每遍历出一条商品数据，就把对应的销量，库存还原回去
            foreach ($arr as $v) {
                $reserve = DB::table('shop_goods_attrs')->where('id', $v->attr_id)->value('reserve');
                $goods_id = DB::table('shop_goods_attrs')->where('id', $v->attr_id)->value('goods_id');
                $buyNum = DB::table('shop_goods')->where('id', $goods_id)->value('buy_num');
                DB::table('shop_goods')->where('id', $goods_id)->update(['buy_num' => $buyNum - $v->buynum]);
                DB::table('shop_goods_attrs')->where('id', $v->attr_id)->update(['reserve' => $reserve + $v->buynum]);
            }

            //改完该订单表对应的商品详细数据，再把该订单的状态改为超时取消
            DB::table('shop_orders')->where('id', $this->orderId)->update(['status' => 3]);
        }

    }
}
